<template>
  <drawer-box>
    <template v-slot:content>
      <el-form
        class="m7-form"
        :label-position="labelPosition"
        :rules="rules"
        :model="formData"
        size="mini"
        ref="nodeForm"
      >
        <el-form-item label="节点名称" prop="name">
          <el-input v-model.trim="formData.name" size="mini" maxlength="40"></el-input>
        </el-form-item>
        <el-form-item prop="url" :rules="[{ required: true, message: '请求地址必填', trigger: 'change' }]">
          <template v-slot:label>
            <span>
              请求地址
              <el-tooltip
                :show-after="500"
                class="item"
                effect="dark"
                content="为提高安全性，建议使用https：开头的地址对接"
                placement="top"
              >
                <span class="MC_iconfont MC_icon-yiwen-mian tip-span"></span>
              </el-tooltip>
            </span>
          </template>
          <el-input v-model.trim="formData.url" size="mini"></el-input>
        </el-form-item>
        <el-form-item
          label="请求方式"
          prop="method"
          :rules="[{ required: true, message: '请求方式必选', trigger: 'change' }]"
        >
          <el-radio v-model="formData.method" label="0">get</el-radio>
          <el-radio v-model="formData.method" label="1">post</el-radio>
        </el-form-item>
        <el-form-item
          label="传参方式"
          prop="method"
          v-if="formData.method == 1"
          :rules="[{ required: true, message: '传参方式必选', trigger: 'change' }]"
        >
          <el-select v-model="formData.contentType" placeholder="请选择传参方式" filterable clearable>
            <el-option v-for="item in methodList" :label="item.label" :value="item.value" :key="item.label"></el-option>
          </el-select>
        </el-form-item>
        <div v-for="(item, index) in formData.variableList" :key="index">
          <div class="select-group-start">
            <el-form-item label="参数">
              <el-cascader style="width: 100%" v-model="item.key" filterable :options="cascadeList" :props="caProps">
              </el-cascader>
            </el-form-item>
            <el-form-item label="自定义名称" :rules="checkKey" :prop="'variableList.' + index + '.value'">
              <el-input @blur="checkPublic(item.value)" v-model.trim="item.value" size="mini"></el-input>
            </el-form-item>
            <div class="select-oprate">
              <span @click="deleteVariableList(item, index)"
                ><i style="font-size: 20px" class="MC_iconfont MC_icon-shanchu2-xian delete-span"></i
              ></span>
            </div>
          </div>
        </div>
        <div class="addVariableList">
          <span @click="addVariableList"><i class="MC_iconfont MC_icon-tianjia-xian add-span"></i>添加参数</span>
        </div>
        <el-form-item
          label="请求超时"
          prop="requestTimeOut"
          :rules="{ required: true, message: '请输入正整数, 最大值为60', pattern: /(^([1-5])?[0-9]$)|^60$/ }"
        >
          <el-input v-model.trim="formData.requestTimeOut" :step="1" step-strictly>
            <template v-slot:append>秒</template>
          </el-input>
        </el-form-item>
        <el-form-item
          label="连接超时"
          prop="connectTimeOut"
          :rules="{ required: true, message: '请输入正整数, 最大值为60', pattern: /(^([1-5])?[0-9]$)|^60$/ }"
        >
          <el-input v-model.trim="formData.connectTimeOut" :step="1" step-strictly>
            <template v-slot:append>秒</template>
          </el-input>
        </el-form-item>
        <el-form-item
          label="返回超时"
          prop="responseTimeOut"
          :rules="{ required: true, message: '请输入正整数, 最大值为60', pattern: /(^([1-5])?[0-9]$)|^60$/ }"
        >
          <el-input v-model.trim="formData.responseTimeOut" :step="1" step-strictly>
            <template v-slot:append>秒</template>
          </el-input>
        </el-form-item>
        <p class="instructions"><i class="MC_icon-xinxi-mian MC_iconfont"></i>使用须知</p>
        <p class="details">
          1.返回值需要是一层的json结构；<br />
          2.返回的值会存入对应的参数中；<br />
          3.为避免和系统变量混淆,除了code外的接口返回字段增加customer_前缀；<br />
          4.返回值中，code参数需要等于200才会认定交互成功，否则将进入失败转向；<br />
          5.参数数据类型均为字符串格式。
        </p>
        <el-form-item :label="item.label" prop="region" v-for="(item, index) in condition" filterable :key="index">
          <template v-slot:label>
            <span>
              {{ item.label }}
              <el-tooltip :show-after="500" class="item" effect="dark" :content="tipMap[index]" placement="top">
                <span class="MC_iconfont MC_icon-yiwen-mian tip-span"></span>
              </el-tooltip>
            </span>
          </template>
          <el-select v-model="item.to" placeholder="请选择下一步节点" clearable style="width: 100%">
            <el-option
              v-for="(node, index) in nodeList"
              :label="node.data.name"
              :value="node.id"
              v-show="!node.viewOnly && node.id !== currentData.id && node.id !== 'startNode'"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </template>
    <template v-slot:operation>
      <el-button @click="cancel" size="mini">取消</el-button>
      <el-button type="primary" @click="onSubmit" size="mini">确定</el-button>
    </template>
    <template v-slot:remove>
      <el-button @click="deleteNode" type="danger" :icon="Delete" size="mini">删除</el-button>
    </template>
  </drawer-box>
</template>

<script lang="ts" setup>
/* eslint-disable vue/no-mutating-props */
import drawerBox from '@/app/call-center/components/drawer-box.vue'
import { withDefaults, defineProps, ref, computed, onMounted, reactive, toRefs } from 'vue'
import useNodeCommon from './use-node-common'
import { Delete } from '@element-plus/icons-vue'
import { cloneDeep } from 'lodash'
import http from '@/common/utils/http'
import { ElMessage } from 'element-plus'
const nodeForm: any = ref(null)
const props = withDefaults(
  defineProps<{
    data: any
    currentNode: any
    save: (...arg: any) => void
    cancel: () => void
    delete: (...arg: any) => void
  }>(),
  {
    data: {},
    currentNode: {}
  }
)
const { nodeList, currentData, labelPosition, rules, formData, condition, cancel, onSubmit, deleteNode }: any =
  useNodeCommon({
    data: props.data,
    currentNode: props.currentNode,
    nodeForm,
    save: props.save,
    cancel: props.cancel,
    delete: props.delete
  })

interface State {
  publicList: any[]
  caProps: Record<string, unknown>
}

const state: State = reactive({
  publicList: [],
  caProps: { label: 'memo', value: 'key', emitPath: false }
})

const tipMap: any = {
  0: '数据交互成功，执行此节点。可选当前流程中其他节点+挂断（不选择即为挂断）。',
  1: '返回结果code非200的所有情况执行此节点。可选当前流程中其他节点+挂断（不选择即为挂断）。',
  2: '请求/连接/返回，任意超时则走此转向。可选当前流程中其他节点+挂断（不选择即为挂断）'
}

const methodList = [
  { label: 'application/x-www-form-urlencoded', value: '1' },
  { label: 'multipart/form-data', value: '2' },
  { label: 'application/json', value: '3' }
]

const minData: any = {
  key: '',
  value: ''
}

const customParametersList: any = computed(() => {
  const arr = cloneDeep(props.data.nodeList)
  const list = arr.find((item: any) => item.id === 'startNode').data?.customList?.filter((i: any) => i.key) || []
  for (let i = 0; i < list.length; i++) {
    const element = list[i]
    element.memo = `${element.key} ${element.memo}`
  }
  return list
})

const cascadeList: any = computed(() => {
  // 参数级联数据
  const list = [
    {
      key: 'fixed',
      memo: '系统参数',
      children: state.publicList
    },
    {
      key: 'custom',
      memo: '自定义参数',
      children: customParametersList.value
    }
  ]
  return customParametersList.value?.length ? list : list.filter((_: any, index: number) => index === 0)
})

const checkKey = computed(() => {
  const keyList = formData.value.variableList.map((i: any) => i.value) || []
  const publicList = state.publicList?.map((i) => i.key) || []
  const checkKey = (_: any, value: any, callback: any) => {
    if (!new RegExp('^[A-Za-z0-9_]{0,50}$').test(value)) {
      callback(new Error('支持大小写英文+数字+下划线格式，区分大小写，至多50字符'))
    } else if (value && keyList.filter((i: any) => i === value).length > 1) {
      callback(new Error('自定义名已存在'))
    } else if (publicList.includes(value)) {
      callback(new Error('与系统参数冲突'))
    } else {
      callback()
    }
  }
  return { trigger: 'blur', validator: checkKey }
})

const getPublicCustom = () => {
  const url = '/call/web/call/action/config/ivr/system-var/cache'
  http({ url, method: 'get' }).then((res) => {
    if (res.success) {
      state.publicList = res.data || []
    }
  })
}

onMounted(() => {
  getPublicCustom()
  if (!props.currentNode.data.variableList) {
    props.currentNode.data.variableList = [cloneDeep(minData)]
  }
})

const addVariableList = () => {
  if (formData.value.variableList.length > 100) {
    ElMessage.warning('条数不能超过100')
    return
  }
  formData.value.variableList.push(cloneDeep(minData))
}

const deleteVariableList = (item: any, i: number) => {
  if (formData.value.variableList.length > 1) {
    formData.value.variableList.splice(i, 1)
  }
}

const checkPublic = (val: any) => {
  const list = state.publicList.map((i) => i.key)
  if (list.includes(val)) {
    ElMessage.warning(`系统变量中含有${val}, 请输入其他变量名`)
  }
}
// eslint-disable-next-line no-undef
defineExpose({
  form: nodeForm
})

const { caProps } = toRefs(state)
</script>
<style lang="stylus" scoped>
$config-color = #a5a5ad
.audioProgress
  margin 0 10px 0
.tip-span
  color $icon-gray
  font-size 12px
  cursor pointer
.has-config
  display flex
  align-items center
  .V7_iconfont
    margin-left 10px
    cursor pointer
    color $config-color
.select-group-start
  display flex
  :deep(.el-form-item)
    width 50%
    margin-right 10px
.delete-span
  cursor pointer
  &:hover
    color $c-danger
.add-span
  font-size 12px
  cursor pointer
  &:before
    margin-right 4px
.select-oprate
  display: flex;
  align-items: center;
  position: relative;
  top: 5px;
  left: 0;
.addVariableList
  font-size: 12px;
  font-weight: 400;
  color: #008BEE;
  line-height: 44px;
  cursor pointer
.instructions
  height: 14px;
  line-height 14px
  font-size: 12px;
  font-weight: 600;
  color: #303753;
  margin-bottom 12px
  i
    font-size 14px
    color #FAAE14
    margin-right 5px
.details
  font-size: 12px;
  font-weight: 400;
  color: #767E91;
  margin-left 7px
  margin-bottom 39px
</style>
